package toy.keli.picmap;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import toy.keli.picmap.model.def;
import toy.keli.picmap.model.system;
import toy.keli.picmap.tools.Tools;
import toy.keli.picmap.util.utilCallback;

public class BaseActivity extends AppCompatActivity {
    utilCallback.func PermissionOkCallback;
    @RequiresApi(api = Build.VERSION_CODES.M)
    public  boolean getPermission() {
        return getPermission(Manifest.permission.READ_EXTERNAL_STORAGE,true);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public boolean getPermission(String premission,boolean tryGet) {
        int readExSD = checkSelfPermission(premission);
        if (readExSD != PackageManager.PERMISSION_GRANTED) {
            // 请求获取权限
            Log.d("info", "request permission...");
            if(tryGet)
            requestPermissions(new String[]{premission}, 1);
            return false;
        } else {
            Log.d("info", "permission has granted");
        }
        return true;
    }

    //只要有一个符合就返回true
    @SuppressLint("NewApi")
    public boolean getPermission(String ...premissions) {
        for(int i=0;i<premissions.length;i++)
            if(getPermission(premissions[i],true)) return true;
        return false;
    }
    @SuppressLint("NewApi")
    public boolean getPermission(String premission,utilCallback.func func) {
        PermissionOkCallback=func;
        if(getPermission(premission,true)) return true;
        return false;
    }
    //所有条件必须都符合
    @SuppressLint("NewApi")
    public boolean getPermissions(String[] premissions) {
        for(int i=0;i<premissions.length;i++)
            if(!getPermission(premissions[i],true)) return false;
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length == 0 || PackageManager.PERMISSION_GRANTED != grantResults[0]) {
            Toast.makeText(this,"你拒绝了权限，无法创建!",Toast.LENGTH_LONG).show();
        }else {
            //在这执行你创建文件的代码
            if(PermissionOkCallback!=null) PermissionOkCallback.call();
        }
    }


    public Dialog simpDialog(View v) {
        return simpDialog(v,false);
    }
    public Dialog simpDialog(View v,boolean full) {
        Dialog dialog = full? new Dialog(this, R.style.FullActivity): new Dialog(this);
        dialog.setContentView(v);
        dialog.show();
        return dialog;
    }

    public static interface callback{
        public void call();
    }
    public static interface callbackStr{
        public void call(String s);
    }
    public static interface callbackObj{
        public void call(Object o);
    }

    //模式弹匡
    public Dialog layoutDialog(int id){
        Dialog dialog = new Dialog(this);
        dialog.setContentView(id);
        return dialog;
    }
    //确认对话框
    public void ConfirmDialog(String title,String msg,callback okDo){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         * android 8种对话框（Dialog）使用方法汇总  https://www.cnblogs.com/gzdaijie/p/5222191.html
         */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
//        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle(title);
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        okDo.call();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * 获取页面元素
     * @param c  元素类型
     * @return
     */
    public def getViewsByTagName(Class c) {
        return getViewsByTagName(this.getWindow().getDecorView(),c);
    }
    public static def getViewsByTagName(View view, Class c) {
        List allchildren=getAllChildViews(view);
        def rt=new def();
        for(int i=0;i<allchildren.size();i++){
            View v=(View)allchildren.get(i);

            if(c.isInstance(v)) {
                String k= String.valueOf(v.getTag());
                rt.set(k,v);
            }
        }
        return rt;
    }
    //android 获取多个控件  https://blog.csdn.net/weixin_32865039/article/details/117568586
    public static List getAllChildViews(View view) {
        List allchildren = new ArrayList();

        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                allchildren.add(viewchild);
                allchildren.addAll(getAllChildViews(viewchild));
            }
        }
        return allchildren;
    }

    public void msg(String str){
        msg(str,Toast.LENGTH_SHORT);
    }

    public void msg(String str,int sd){
        Toast.makeText(this, str, sd).show();
    }
    public void systemCopy(String str){
        system.copy(this,str);
        system.msg(this,"内容复制成功");
    }

    public PopupMenu popupMenu(View v,String[] items,callbackStr f) {
        return popupMenu(v,items,-1,(i)->{
            f.call(((MenuItem)i).getTitle().toString());
        });
    }
    public PopupMenu popupMenu(View v,String[] items,int select,callbackObj click) {
        //定义PopupMenu对象
        PopupMenu pm = new PopupMenu(this, v);
        Menu m = pm.getMenu(); int i=0;
        for(String item: items) {
            m.add(0,i++,0,item);
        }
        if(select>-1) {
            m.getItem(select).setCheckable(true);
            m.getItem(select).setChecked(true);
        }
        popupMenu(pm,click);
        return pm;
    }
    //弹出菜单  https://www.jb51.net/article/177024.htm
    public PopupMenu popupMenu(View v, int vid, callbackObj click) {
        //定义PopupMenu对象
        PopupMenu pm = new PopupMenu(this, v);
        //设置PopupMenu对象的布局
        pm.getMenuInflater().inflate(vid, pm.getMenu());
        popupMenu(pm,click);
        return pm;
    }
    private PopupMenu popupMenu(PopupMenu popupMenu ,callbackObj click) {
        Context ct=this;
        //设置PopupMenu的点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                click.call(item);
                return true;
            }
        });

        //显示菜单
        popupMenu.show();
        return popupMenu;
    }

    public void prompt(String title,String data,callbackStr func){
        AlertDialog mDialog=null;
        LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.prompt, null);
        TextView input = view.findViewById(R.id.editText_prompt);
        input.setText(data);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setIcon(R.drawable.control);
        //之前inflate的View 放到dialog中
        builder.setView(view);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                func.call(String.valueOf(input.getText()));
              //  mDialog.hide();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //mDialog.hide();
            }
        });
        mDialog=builder.create();
        mDialog.show();
    }

    public void openApp(String appid){
        openApp(appid,null,null);
    }
    public void openApp(String appid, String path, utilCallback.intent func){
        Intent intent = new Intent();

        ComponentName componentName =  new ComponentName(appid,path);
        intent.setComponent(componentName);
        if(func!=null) func.call(intent);
        startActivity(intent);
    }

    ApplicationInfo getAppInfo(String name){
        try {
            return getPackageManager().getApplicationInfo(name,PackageManager.GET_UNINSTALLED_PACKAGES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    //
    List<String> appAll(){

        List pinfo = this.getPackageManager().getInstalledPackages(0);
        ArrayList<String> rt=new ArrayList<String>();
        for (int i = 0; i < pinfo.size(); i++) {
            String name = ((PackageInfo) pinfo.get(i)).packageName;
            rt.add(name);
        }
        return rt;
    }

    String argv(String name){
        Intent intent = getIntent();
        String str=intent.getStringExtra(name);
//        if(str==null) str="";
        return str;
    }

    //Android 开发 屏幕常亮的3个方法  https://www.cnblogs.com/guanxinjing/p/10950251.html
    public void keepScreenOn(boolean on){
        if(on)
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        else
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    def attrs=new def();
    Object __get(Class c){
        String name=c.getName();
        if(attrs.hasKey(name)) return attrs.get(name).source();
        Tools newObj= null;
        try {
            newObj =(Tools)Class.forName(c.getCanonicalName()).newInstance();
            newObj.bindActivity(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        attrs.set(name,newObj);
        return newObj;
    }
}
